<?php

namespace app\api\model;



use app\common\model\User;
use think\Db;
use think\Model;


//用户升级记录
class UserUpgradeLog extends Model
{
    // 表名
    protected $name = 'user_upgrade_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;


    public static function log($user_id,$level,$memo,$after_level_star=-1,$is_buy_699=0)
    {
        Db::startTrans();
        try {
            $user = User::lock(true)->find($user_id);

            if ($user && $level != 0) {
                $before_level = $user->level;
                $before_level_star = $user->level_star;
                //更新会员信息
                $data =['level' => $level];
                if ($after_level_star>0)$data['level_star'] = $after_level_star;
                if ($is_buy_699)$data['is_buy_699'] = 1;

                $user->save($data);
                //写入日志
                $log_data = ['user_id' => $user_id, 'before_level' => $before_level, 'after_level' => $level,'memo' => $memo];
                if ($after_level_star>=0){
                    $log_data['before_level_star'] = $before_level_star;
                    $log_data['after_level_star'] = $after_level_star;
                }
                UserUpgradeLog::create($log_data);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }
}